Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

var record_start = 0; 

var sm = new Ext.grid.CheckboxSelectionModel();
var cm=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",width:40,
renderer:function(value,metadata,record,rowIndex){ 
	return record_start + 1 + rowIndex; 
} 
}),
{header:'抵质押品代码',dataIndex:'collateralId',width:100},
{header:'抵质押品名称',dataIndex:'collateralName',width:100},
{header:'抵质押品类型',dataIndex:'collateralType',width:100},
{header:'抵质押品当前评估价值',dataIndex:'nowValue',width:100}
]); 

var ds=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'obligation/listCollateral.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader({
	totalProperty:'total',  
	root:'collateral'
},[
{name:'collateralId'},
{name:'collateralName'}, 
{name:'collateralType'},  
{name:'nowValue'}
]) 
}); 
ds.load({params:{start:0,limit:20}}); 

var collateralTypeLevelOneStore = new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showColTypeLevelOne.do',
method:'GET'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'code'}, 
{name:'name'}
]) ,
autoLoad:true
}); 
var yesOrNoStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'showType.do?type=YesNo',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad:true
	});
var publishStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'showType.do?type=Publish',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad:true
	});
var yearStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'showType.do?type=YearLimit',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad:true
	});
var currencyStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'showType.do?type=Currency',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad:true
	});

var collateralTypeLevelTwoStore = new Ext.data.Store({ 
reader:new Ext.data.JsonReader({ },[
{name:'code'}, {name:'name'}
])
});

var conditionStore = new Ext.data.SimpleStore({
	   fields : ['id', 'text'],
	   data : [['collateralId', '抵质押品编号'], ['collateralName', '抵质押品名称']]
});

var grid=new Ext.grid.GridPanel({ 
id:'contentList',
renderTo:"list", 
stripeRows:true,//斑马线效果
title:"抵质押品列表", 
height:500, 
cm:cm,
store: ds, 
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 20,   
                store: ds,   
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据"  ,
                doLoad : function(start){ 
                	   record_start = start; 
                	var o = {}, pn = this.getParams(); 
                	          o[pn.start] = start; 
                	          o[pn.limit] = this.pageSize; 
                	this.store.load({params:o}); 
                 }  
            }),
 tbar: [
	 {text:'新增',id: 'btnAdd'},
 '-',
 {text:'查看/编辑',handler:checkDetail},
 '-',
 {text:'删除',handler:del},
 '->',
 	{xtype:'combo',
     id:'condition',
     name: 'condition', 
     store: conditionStore,
     fieldLabel: '请选择查询条件',
     valueField : 'id',
     displayField : 'text',
     emptyText : '请选择查询条件',
     triggerAction : 'all',
     editable: false,
     mode:'local',
     width:110
     },'',
     {xtype:'textfield',id:'keyword',width:180},
     {text:'查询',handler:findCustomer},
     '-',
     {text:'清空',handler: callBack}  
 ]              
});

function findCustomer(){

var condition = Ext.getCmp('condition').getValue();
var keyword = Ext.getCmp('keyword').getValue();

if(condition == '' || condition == null){
	Ext.Msg.alert('提示', '请选择查询条件！'); 
}
else{

	ds.baseParams={condition:condition, keyword: keyword};
	ds.proxy = new Ext.data.HttpProxy({
					url:'obligation/findCollateral.do',
					method:'POST'
				}); 
	ds.reader = new Ext.data.JsonReader({ 
						totalProperty:'total',  
						root:'resultData'},[
						{name:'collateralId', mapping: 'collateralId'}, 
						{name:'collateralName', mapping: 'collateralName'},  
						{name:'collateralType', mapping: 'collateralType'},
						{name:'nowValue', mapping: 'nowValue'},
					]);
					   
	ds.load({params:{start:0,limit:20}});
	record_start = 0;  	
}
}

function callBack(){

Ext.getCmp('condition').clearValue();
Ext.getCmp('keyword').setValue('');
	ds.proxy = new Ext.data.HttpProxy({
					url:'obligation/findCollateral.do',
					method:'POST'
				}); 
	ds.reader = new Ext.data.JsonReader({ 
						totalProperty:'total',  
						root:'resultData'},[
						{name:'collateralId', mapping: 'collateralId'}, 
						{name:'collateralName', mapping: 'collateralName'},  
						{name:'collateralType', mapping: 'collateralType'},
						{name:'nowValue', mapping: 'nowValue'},
					]);   
	ds.load({params:{start:0,limit:20}});
	record_start = 0;

}


//新增表单
var addForm = new Ext.form.FormPanel({ 
id: 'addForm', 
width: 640, 
height: 450, 
//样式 
bodyStyle: 'margin:3px 3px 3px 3px', 
frame: true, 
xtype: 'filedset', 
labelWidth: 160, 
items: 
[ { xtype: 'fieldset', 
title: '抵质押品信息', 
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[{layout : "form",
items : [{
xtype: 'textfield',
id: 'collateralName', 
name: 'collateralName', 
fieldLabel: '抵质押品名称',
allowBlank: true,  
width: 130 
}
]},
{
layout : "form",
items : [{
	  xtype: 'combo', 
			id: 'collateralLevelOneType', 
			name: 'collateralLevelOneType', 
              store :collateralTypeLevelOneStore,
              fieldLabel: '抵质押品类型',
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择抵质押品类型...',
              allowBlank : false,
              blankText:'请选择抵质押品类型',
              editable: false,
              typeAhead : true,
              width: 180,
              mode:'local', 
              hiddenName:'collateralLevelOneType',
              triggerAction : 'all',
              selectOnFocus : true,
              listeners:{        
		           select : function(combo, record,index)   
		           {   
					var collateralTypeCombo = Ext.getCmp('collateralType');
		            collateralTypeCombo.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
		
		            collateralTypeLevelTwoStore.proxy =new Ext.data.HttpProxy({
					url:'showColTypeLevelTwo.do?levelOneCode='+combo.value,
					method:'POST'
					});
		            collateralTypeLevelTwoStore.load();
		            
		            if(combo.value == '0401') {
		            	Ext.getCmp('publish').setVisible(true);
		            	Ext.getCmp('year').setVisible(true);
		            	Ext.getCmp('currency').setVisible(true);
		            	
		            }
					else if(combo.value == '0402') {
						Ext.getCmp('currency').setVisible(true);
		            	Ext.getCmp('publish').setVisible(false);
		            	Ext.getCmp('year').setVisible(false);
					}
					else{
						Ext.getCmp('currency').setVisible(false);
		            	Ext.getCmp('publish').setVisible(false);
		            	Ext.getCmp('year').setVisible(false);
					}
		            
		           }      
       }
}, {
	  xtype: 'combo', 
			id: 'collateralType', 
			name: 'collateralType', 
              store :collateralTypeLevelTwoStore,
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择抵质押品类型...',
              allowBlank : false,
              blankText:'请选择抵质押品类型',
              editable: false,
              typeAhead : true,
              width:430,
              mode:'local', 
              hiddenName:'collateralType',
              triggerAction : 'all',
              selectOnFocus : true 
}]
},{
	layout:"column",
	items:[{ columnWidth : .5, 
	           layout : "form",
	           items : [{
	xtype: 'textfield',
	id: 'nowValue', 
	name: 'nowValue', 
	fieldLabel: '抵质押品当前评估价值（元）',
	allowBlank: true,  
	width: 130 
	}]} ,{ columnWidth : .5, 
        layout : "form",
        items : [{
     	   xtype: 'combo', 
				 id : "currency",
	              store :currencyStore,
	              fieldLabel: '币种',
	              valueField : 'code',
	              displayField : 'name',
	              typeAhead : true,
	              width: 130,
	              allowBlank : true,
	              mode:'remote', 
	              editable: false,
	              triggerAction : 'all',
	              selectOnFocus : true,
	              allowBlank: true,
	              hiddenName:'currency' 
}]}
	]},
{
	layout:"column",
	items:[{
		columnWidth : .5, // 该列有整行中所占百分比
	           layout : "form",
	           items : [{
	        	   xtype: 'combo', 
					 id : "publish",
		              store :publishStore,
		              fieldLabel: '发行方<font color=red>(必选)</font>',
		              valueField : 'code',
		              displayField : 'name',
		              typeAhead : true,
		              width: 130,
		              allowBlank : true,
		              mode:'remote', 
		              editable: false,
		              triggerAction : 'all',
		              selectOnFocus : true,
		              hiddenName:'publish'
	}
	]},{ columnWidth : .5, 
	           layout : "form",
	           items : [{
	        	   xtype: 'combo', 
					 id : "year",
		              store :yearStore,
		              fieldLabel: '年限<font color=red>(必选)</font>',
		              valueField : 'code',
		              displayField : 'name',
		              typeAhead : true,
		              width: 130,
		              allowBlank : true,
		              mode:'remote', 
		              editable: false,
		              triggerAction : 'all',
		              selectOnFocus : true,
		              hiddenName:'year' 
	}]} 
	]},
	
{
	layout:"column",
	items:[{
		columnWidth : .5, // 该列有整行中所占百分比
	           layout : "form",
	           items : [{
	           xtype: 'datefield',
	id: 'collateralTerm', 
	name: 'collateralTerm', 
	fieldLabel: '抵质押品有效起始日',
	allowBlank: true,  
	width:130,
	format : 'Y-m-d'
	}
	]},{ columnWidth : .5, 
	           layout : "form",
	           items : [{
	        	   xtype: 'datefield',
		   			id: 'endTerm', 
		   			name: 'endTerm', 
		   			fieldLabel: '抵质押品有效到期日',	   
		   			format : 'Y-m-d',
					width: 130 
	}]} 
	]},
{
layout:"column",
items:[{
	columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
           xtype: 'datefield',
id: 'loanValueDate', 
name: 'loanValueDate', 
fieldLabel: '审批放款时评估时间',
allowBlank: true,  
width:130,
format : 'Y-m-d'
}
]},{ columnWidth : .5, 
           layout : "form",
           items : [{
xtype: 'textfield',
id: 'loanValue', 
name: 'loanValue', 
fieldLabel: '审批放款时评估价值（元）',
allowBlank: true,  
width: 130 
}]} 
]},{
layout:"column",
items:[{
	columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
           xtype: 'datefield',
id: 'dealValueDate', 
name: 'dealValueDate', 
fieldLabel: '处置时评估时间',
allowBlank: true,  
width:130,
format : 'Y-m-d'
}
]},{ columnWidth : .5, 
           layout : "form",
           items : [{
xtype: 'textfield',
id: 'dealValue', 
name: 'dealValue', 
fieldLabel: '处置时评估价值（元）',
allowBlank: true,  
width: 130 
}]} 
]},{
	layout:"column",
	items:[{
		columnWidth : .5, // 该列有整行中所占百分比
	           layout : "form",
	           items : [{
	           xtype: 'datefield',
	id: 'recoverDate', 
	name: 'recoverDate', 
	fieldLabel: '最终收回时间',
	allowBlank: true,  
	width:130,
	format : 'Y-m-d'
	}
	]},{ columnWidth : .5, 
        layout : "form",
        items : [{
xtype: 'textfield',
id: 'recoverValue', 
name: 'recoverValue', 
fieldLabel: '最终回收金额（元）',
allowBlank: true,  
width: 130 
}]} 
	]},{
		layout:"column",
		items:[{
			columnWidth : .5, // 该列有整行中所占百分比
		           layout : "form",
		           items : [{
		        	   xtype: 'combo', 
						 id : "belongFlag",
			              store :yesOrNoStore,
			              fieldLabel: '所有权属于借款人',
			              valueField : 'code',
			              displayField : 'name',
			              typeAhead : true,
			              width: 130,
			              allowBlank : true,
			              mode:'remote', 
			              editable: false,
			              triggerAction : 'all',
			              selectOnFocus : true,
			              allowBlank: true,
			              hiddenName:'belongFlag'
		}
		]},{ columnWidth : .5, 
		           layout : "form",
		           items : [{
		xtype: 'textfield',
		id: 'bankShare', 
		name: 'bankShare', 
		fieldLabel: '该抵押品在我行份额(%)',
		allowBlank: true,  
		width: 130 
		}]} 
		]},
		{
			layout : "form",
	        items : [{
				xtype: 'textarea',
				id: 'otherInfo', 
				name: 'otherInfo', 
				fieldLabel: '其他说明（限100汉字以内）',
				allowBlank: true,  
				width: 430 
	        }]
		},
{xtype:'hidden',
id:'collateralId',
name:'collateralId'
}
] 
}]
});

//新增窗口 
addWin = new Ext.Window({ 
id: 'addWin', 
title: '抵质押品', 
width: 660, 
height: 450, 
//背景遮罩 
modal: true, 
//重置大小 
resizable: false, 
//当关闭按钮被点击时执行的动作 
closeAction: 'hide', 
plain: true, 
buttonAlign: 'right', 
items:addForm, 
buttons: 
[  
{ text: '保存', id: 'btnSubmit' } ,
{ text: '关闭', handler: function() { Ext.getCmp('addWin').hide(); } }

] 
});

function addFunction() {

	if(addForm.form.isValid()){
		addForm.form.doAction('submit', { 
			url : 'obligation/addCollateral.do', 
			method : 'post', 
			success : function() { 
			Ext.getCmp('addWin').hide();
			grid.store.reload();
			Ext.Msg.alert('提示', '添加成功！'); 
			}, 
			failure : function() { 
			Ext.Msg.alert('提示', '添加失败！'); 
			} 
		});  
	}
}

//添加按钮单击事件 
function btnAddClick() { 
Ext.getCmp('addForm').form.reset(); 
Ext.getCmp("addWin").buttons[0].handler = addFunction; 
Ext.getCmp("addWin").show(); 
}; 

//新增按钮 
var addUserBtn = Ext.getCmp('btnAdd'); 
addUserBtn.on('click', btnAddClick); 

//删除客户
function del(){
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
	Ext.Msg.alert("提示", "请选中要删除的内容"); 
} 
else{
	Ext.MessageBox.confirm('提示', '确实要删除所选的内容吗？', deleteConfirm);
}
}

function deleteConfirm(btn){
if (btn == 'yes') {
 Ext.Ajax.request({
  url:'obligation/deleteCollateral.do',
  params : {collateralId : grid.getSelectionModel().getSelections()[0].data.collateralId},
  method:'POST',
  success:function(response){
	  var json = Ext.util.JSON.decode(response.responseText);
	  if(json.del == true){
		  Ext.MessageBox.alert("提示","删除成功！");
	   	grid.store.reload(); 
	  }
	  else if(json.del == false){
		  Ext.MessageBox.alert("提示","该抵质押品与债项有关联，不能删除！");
	  }
	   
  },failure:function(){
    Ext.MessageBox.alert("提示", "删除失败！"); 
  }
});
}
}

function editFunction(){
	
if(addForm.form.isValid()){
	 addForm.form.doAction('submit', { 
        url : 'obligation/editCollateral.do', 
        method : 'post', 
		success : function() { 
			grid.store.reload();
			Ext.Msg.alert('提示', '保存成功！'); 
		}, 
        failure : function() { 
			Ext.Msg.alert('提示', '保存失败！'); 
 		} 
	}); 
}
}

function checkDetail(){
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要查看的内容！"); 
}
else{
	var selectedId = grid.getSelectionModel().getSelections()[0].data.collateralId;
           
   	addForm.form.reset(); 
	
	addWin.buttons[0].handler = editFunction; 

	Ext.Ajax.request({
		url:'obligation/getCollateral.do',
		params : { collateralId: selectedId},
		method:'POST',
  		success:function(response){
		 	var json = Ext.util.JSON.decode(response.responseText);
		 	Ext.getCmp("collateralId").setValue(json.collateralId);
		  	Ext.getCmp("collateralName").setValue(json.collateralName);
			Ext.getCmp("collateralType").setValue(json.collateralTypeLevelTwoName);
			Ext.getCmp("collateralLevelOneType").setValue(json.collateralTypeLevelOneName);
			Ext.getCmp("endTerm").setValue(json.endTerm);
		  	Ext.getCmp("collateralTerm").setValue(json.collateralTerm);
			Ext.getCmp("nowValue").setValue(json.nowValue);
		   	Ext.getCmp("loanValueDate").setValue(json.loanValueDate);
			Ext.getCmp("loanValue").setValue(json.loanValue);
			Ext.getCmp("dealValueDate").setValue(json.dealValueDate);
		  	Ext.getCmp("dealValue").setValue(json.dealValue);
		  	Ext.getCmp("recoverDate").setValue(json.recoverDate);
		  	Ext.getCmp("bankShare").setValue(json.bankShare);
		  	Ext.getCmp("recoverValue").setValue(json.recoverValue);
		  	Ext.getCmp("belongFlag").setValue(json.belongFlag);
		  	Ext.getCmp("otherInfo").setValue(json.otherInfo);
		  	Ext.getCmp("publish").setValue(json.publish);
		  	Ext.getCmp("year").setValue(json.year);
		  	Ext.getCmp("currency").setValue(json.currency);
		  	
		  	if(json.collateralTypeLevelOneName == '0401') {
            	Ext.getCmp('publish').setVisible(true);
            	Ext.getCmp('year').setVisible(true);
            	Ext.getCmp('currency').setVisible(true);
            	
            }
			else if(json.collateralTypeLevelOneName == '0402') {
				Ext.getCmp('currency').setVisible(true);
            	Ext.getCmp('publish').setVisible(false);
            	Ext.getCmp('year').setVisible(false);
			}
			else{
				Ext.getCmp('currency').setVisible(false);
            	Ext.getCmp('publish').setVisible(false);
            	Ext.getCmp('year').setVisible(false);
			}
		  	
		  	
			Ext.getCmp("addWin").show(); 
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
}); 
}
}

grid.addListener('rowdblclick',checkDetail);
}); 